/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-04-29 15:12:45
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-09-24 17:26:42
 * @FilePath: /vue3-admin/src/service/biz/useDept.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import {
    readDeptTree,
    DeptParam,
    createOrUpdateDept,
    deleteItem
} from '@/api/department';
import { ref } from 'vue';
import type { DeptTreeItem } from '@/typings/api/department';
import { useEnum } from '@/service/useEnum';

export { DeptParam };

export const useDept = () => {
    const tree = ref<DeptTreeItem[]>([]);
    const loading = ref(false);
    const { getDeptTreeTypes } = useEnum();
    const { update: deptTreeTypesUpdate } = getDeptTreeTypes();

    const getTree = () => {
        if (loading.value) return;
        loading.value = true;
        return readDeptTree()
            .then((res) => {
                tree.value = res.data;
                return res;
            })
            .finally(() => {
                loading.value = false;
            });
    };

    // const detail = ref<CategoryDetail>();
    // const detailLoading = ref(false);

    // const getDetail = (id: number) => {
    //     if (detailLoading.value) return;
    //     detailLoading.value = true;
    //     return queryCategoryDetail(id)
    //         .then(res => {
    //             detail.value = res.data;
    //             return res;
    //         })
    //         .finally(() => {
    //             detailLoading.value = false;
    //         });
    // };

    const updateLoading = ref(false);
    const updateItem = (param: DeptParam) => {
        if (updateLoading.value) return;
        updateLoading.value = true;
        return createOrUpdateDept(param)
            .then(() => {
                deptTreeTypesUpdate();
            })
            .finally(() => {
                updateLoading.value = false;
            });
    };

    const removeLoading = ref(false);
    const removeItem = (id: number) => {
        if (removeLoading.value) return;
        removeLoading.value = true;
        return deleteItem(id)
            .then((res) => {
                deptTreeTypesUpdate();
                return res;
            })
            .finally(() => {
                removeLoading.value = false;
            });
    };

    return {
        loading,
        getTree,
        tree,
        updateItem,
        updateLoading,
        removeLoading,
        removeItem
    };
};
